package com.microtf.inscription.framework.service;

import com.microtf.inscription.framework.vo.user.UserLoginDto;
import com.microtf.inscription.jpa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.LinkedList;

/**
 * 用户帐号登录
 *
 * @author guliuzhong
 * @since 1.0
 */
@Service
public class UserLoginService implements UserDetailsService {
    /**
     * 用户服务
     */
    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户登录
     * <p>暂未实现权限功能</p>
     *
     * @param userName 用户名
     * @return 用户登录结果
     * @throws UsernameNotFoundException 用户不存在
     * @author guliuzhong
     * @since 1.0
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        if (userName == null || userName.isEmpty()) {
            throw new UsernameNotFoundException("用户不存在");
        }
        User user = userService.getUser(userName);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserLoginDto userLoginDto = new UserLoginDto();

        userLoginDto.setUsername(user.getUsername());
        userLoginDto.setPassword(user.getPassword());
        userLoginDto.setAccountNonExpired(user.isAccountNonExpired());
        userLoginDto.setAccountNonLocked(user.isAccountNonLocked());
        userLoginDto.setCredentialsNonExpired(user.isCredentialsNonExpired());
        userLoginDto.setEnabled(user.isEnabled());
        userLoginDto.setUserId(user.getId());

        Collection<GrantedAuthority> grantedAuthorities = new LinkedList<>();

        userLoginDto.setAuthorities(grantedAuthorities);
        return userLoginDto;
    }
}
